package wg.configuration
{

	import flash.filesystem.*;

	public class configuration {
		

		public var prefsFile:File;
		[Bindable] public var prefsXML:XML;
		public var stream:FileStream;
		
		public function configuration(file:String=null) {
			if (file == null) file = "preferences.xml";
			this.prefsFile = File.applicationStorageDirectory.resolvePath(file); 
			
		}
		
		public function getConfiguration():XML {
			return this.readXML();
		}
		
		private function readXML():XML {
			this.stream = new FileStream();
			if (this.prefsFile.exists) return this.processXMLData();
			else return new XML();
		}
		
		private function processXMLData():XML {
			this.stream.open(this.prefsFile, FileMode.READ);
			this.prefsXML = XML(this.stream.readUTFBytes(this.stream.bytesAvailable));
			this.stream.close();
			return this.prefsXML;
		}
		
		public function saveConfiguration(conf:Object):void {
			this.writeXMLData(this.getXMLData(conf));
		}
		
		public function getXMLData(conf:Object):String {
			var xml:String = "<configuration>\n";
			for each (var item:Object in conf) xml += '\t<' + item["key"] + '>' + item["value"] + '</' + item["key"] + ">\n";
			xml += "</configuration>";
			return xml;
		}
		
		private function writeXMLData(xml:String):void {
			var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';
			outputString += xml;
			//outputString = outputString.replace(/\n/g, File.lineEnding);
			this.stream = new FileStream();
			this.stream.open(this.prefsFile, FileMode.WRITE);
			this.stream.writeUTFBytes(outputString);
			this.stream.close();
		}

	}
}